package com.linwankaifa.linwancunyi.ui.back;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;

import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.linwankaifa.linwancunyi.R;
import com.linwankaifa.linwancunyi.bean.StaticDataBean;
import com.linwankaifa.linwancunyi.util.JsonTransformation;
import com.linwankaifa.linwancunyi.util.LoadingDialog;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by 余梦麒 on 2019/7/12.
 */

public class BackStatisticalInformation extends AppCompatActivity implements OnChartValueSelectedListener {

    ArrayList<Integer> colors = new ArrayList<Integer>();
    private PieChart patient_gender_chart;
    //    private PieChart doctor_gender_chart;
    private PieChart doctor_position_chart;
    private PieChart chat_chart;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            StaticDataBean getdata = (StaticDataBean) msg.obj;
            setColor();
            ;
            ArrayList<PieEntry> entries1 = new ArrayList<PieEntry>();
            entries1.add(new PieEntry(getdata.getPatientFemaleNumber(), "女患者"));
            entries1.add(new PieEntry(getdata.getPatientMaleNumber(), "男患者"));
            initView(patient_gender_chart, getdata.getPatientNumber());
            setLegend(patient_gender_chart);
            PieDataSet dataSet1 = new PieDataSet(entries1, null);
            //设置饼状Item之间的间隙
            dataSet1.setSliceSpace(3f);
            //设置饼状Item被选中时变化的距离
            dataSet1.setSelectionShift(5f);
            dataSet1.setColors(colors);
            dataSet1.setValueLinePart1OffsetPercentage(80.f);
            dataSet1.setValueLinePart1Length(0.2f);
            dataSet1.setValueLinePart2Length(0.4f);
            dataSet1.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
            PieData data1 = new PieData(dataSet1);
            //设置所有DataSet内数据实体（百分比）的文本字体格式
            data1.setValueFormatter(new PercentFormatter());
            //设置所有DataSet内数据实体（百分比）的文本字体大小
            data1.setValueTextSize(11f);
            data1.setValueTextColor(Color.BLACK);
            patient_gender_chart.setData(data1);
            // 撤销所有的亮点
            patient_gender_chart.highlightValues(null);
            patient_gender_chart.invalidate();

//            ArrayList<PieEntry> entries2 = new ArrayList<PieEntry>();
//            entries2.add(new PieEntry(getdata.getDoctorFemaleNumber(), "女医生"));
//            entries2.add(new PieEntry(getdata.getDoctorMaleNumber(), "男医生"));
//            initView(doctor_gender_chart, getdata.getDoctorNumber());
//            setLegend(doctor_gender_chart);
//            PieDataSet dataSet2 = new PieDataSet(entries2, null);
//            //设置饼状Item之间的间隙
//            dataSet2.setSliceSpace(3f);
//            //设置饼状Item被选中时变化的距离
//            dataSet2.setSelectionShift(5f);
//            dataSet2.setColors(colors);
//            dataSet2.setValueLinePart1OffsetPercentage(80.f);
//            dataSet2.setValueLinePart1Length(0.2f);
//            dataSet2.setValueLinePart2Length(0.4f);
//            dataSet2.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
//            PieData data2 = new PieData(dataSet2);
//            //设置所有DataSet内数据实体（百分比）的文本字体格式
//            data2.setValueFormatter(new PercentFormatter());
//            //设置所有DataSet内数据实体（百分比）的文本字体大小
//            data2.setValueTextSize(11f);
//            data2.setValueTextColor(Color.BLACK);
//            doctor_gender_chart.setData(data2);
//            // 撤销所有的亮点
//            doctor_gender_chart.highlightValues(null);
//            doctor_gender_chart.invalidate();
//            doctor_gender_chart.setDrawHoleEnabled(false);

            ArrayList<PieEntry> entries3 = new ArrayList<PieEntry>();
            entries3.add(new PieEntry(getdata.getDeputyChiefPhysicianNumber(), "副主任医师"));
            entries3.add(new PieEntry(getdata.getAttendingDoctorNumber(), "主治医师"));
            entries3.add(new PieEntry(getdata.getChiefPhysicianNumber(), "主任医师"));
            entries3.add(new PieEntry(getdata.getPhysicianNumber(), "医师"));
            initView(doctor_position_chart, getdata.getDoctorNumber());
            setLegend(doctor_position_chart);
            PieDataSet dataSet3 = new PieDataSet(entries3, null);
            //设置饼状Item之间的间隙
            dataSet3.setSliceSpace(3f);
            //设置饼状Item被选中时变化的距离
            dataSet3.setSelectionShift(5f);
            dataSet3.setColors(colors);
            dataSet3.setValueLinePart1OffsetPercentage(80.f);
            dataSet3.setValueLinePart1Length(0.2f);
            dataSet3.setValueLinePart2Length(0.4f);
            dataSet3.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
            PieData data3 = new PieData(dataSet3);
            //设置所有DataSet内数据实体（百分比）的文本字体格式
            data3.setValueFormatter(new PercentFormatter());
            //设置所有DataSet内数据实体（百分比）的文本字体大小
            data3.setValueTextSize(11f);
            data3.setValueTextColor(Color.BLACK);
            doctor_position_chart.setData(data3);
            // 撤销所有的亮点
            doctor_position_chart.highlightValues(null);
            doctor_position_chart.invalidate();
            doctor_position_chart.setDrawHoleEnabled(false);

            ArrayList<PieEntry> entries4 = new ArrayList<PieEntry>();
            entries4.add(new PieEntry(getdata.getPatientToDoctorChatNumber(), "患者-医生聊天"));
            entries4.add(new PieEntry(getdata.getDoctorToPatientNumber(), "医生-患者聊天"));
            initView(chat_chart, getdata.getChatNumber());
            setLegend(chat_chart);
            PieDataSet dataSet4 = new PieDataSet(entries4, null);
            //设置饼状Item之间的间隙
            dataSet4.setSliceSpace(3f);
            //设置饼状Item被选中时变化的距离
            dataSet4.setSelectionShift(5f);
            dataSet4.setColors(colors);
            dataSet4.setValueLinePart1OffsetPercentage(80.f);
            dataSet4.setValueLinePart1Length(0.2f);
            dataSet4.setValueLinePart2Length(0.4f);
            dataSet4.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
            PieData data4 = new PieData(dataSet4);
            //设置所有DataSet内数据实体（百分比）的文本字体格式
            data4.setValueFormatter(new PercentFormatter());
            //设置所有DataSet内数据实体（百分比）的文本字体大小
            data4.setValueTextSize(11f);
            data4.setValueTextColor(Color.BLACK);
            chat_chart.setData(data4);
            // 撤销所有的亮点
            chat_chart.highlightValues(null);
            chat_chart.invalidate();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_statistical_information);

        patient_gender_chart = (PieChart) findViewById(R.id.patient_gender_chart);
//        doctor_gender_chart = (PieChart) findViewById(doctor_gender_chart);
        doctor_position_chart = (PieChart) findViewById(R.id.doctor_position_chart);
        chat_chart = (PieChart) findViewById(R.id.chat_chart);

        get_data();

        showMyDialog();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    //初始化
    private void initView(PieChart chart, int num) {
        //折现饼状图
        chart.setDrawSliceText(false);
        //使用百分比显示
        chart.setUsePercentValues(true);
        //设置pieChart图表的描述
        chart.getDescription().setEnabled(true);
        Description description = new Description();
        description.setText("总人数：" + String.valueOf(num));
        description.setTextSize(14);
        description.setTextColor(Color.parseColor("#ff9933"));
        chart.setDescription(description);
        //设置pieChart图表上下左右的偏移，类似于外边距
        //设置pieChart图表转动阻力摩擦系数[0,1]
        chart.setDragDecelerationFrictionCoef(0.95f);
        chart.setExtraOffsets(0.f, 0.f, 0.f, 0.f);
        //是否显示PieChart内部圆环(true:下面属性才有意义)
        chart.setDrawHoleEnabled(true);
        //设置PieChart内部圆的颜色
        chart.setHoleColor(Color.WHITE);
        //设置PieChart内部透明圆与内部圆间距(31f-28f)填充颜色
        chart.setTransparentCircleColor(Color.WHITE);
        //设置PieChart内部透明圆与内部圆间距(31f-28f)透明度[0~255]数值越小越透明
        chart.setTransparentCircleAlpha(110);
        //设置PieChart内部圆的半径
        chart.setHoleRadius(58f);
        //设置PieChart内部透明圆的半径
        chart.setTransparentCircleRadius(61f);
        //是否绘制PieChart内部中心文本
        chart.setDrawCenterText(false);
        //设置pieChart图表是否可以手动旋转
        chart.setRotationAngle(0);
        // 触摸旋转
        chart.setRotationEnabled(true);
        chart.setHighlightPerTapEnabled(true);
        // 添加一个选择监听器
        chart.setOnChartValueSelectedListener(this);
        //默认动画
        chart.animateY(1400, Easing.EasingOption.EaseInOutQuad);
    }

    //设置数据
    private void setColor() {
        colors.add(Color.rgb(55, 220, 220));
        colors.add(Color.rgb(255, 193, 0));
        colors.add(Color.rgb(110, 180, 220));
        colors.add(Color.rgb(240, 72, 46));

    }

    public void setLegend(PieChart chart) {
        // 获取pieCahrt图列
        Legend l = chart.getLegend();
        l.setEnabled(true);
        //是否启用图列（true：下面属性才有意义）
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        l.setOrientation(Legend.LegendOrientation.VERTICAL);
        l.setForm(Legend.LegendForm.DEFAULT); //设置图例的形状
        l.setFormSize(12);
        //设置图例的大小
        l.setFormToTextSpace(10f);
        //设置每个图例实体中标签和形状之间的间距
        l.setDrawInside(false);
        l.setWordWrapEnabled(true);
        //设置图列换行(注意使用影响性能,仅适用legend位于图表下面)
        l.setYEntrySpace(4f);
        //设置图例实体之间延X轴的间距（setOrientation = HORIZONTAL有效）
        l.setYOffset(0f);
        //设置比例块Y轴偏移量
        l.setTextSize(15f);
        //设置图例标签文本的大小
        l.setTextColor(Color.parseColor("#ff9933"));
        //设置图例标签文本的颜色
    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {

    }

    @Override
    public void onNothingSelected() {

    }

    public void get_data() {
        OkHttpClient client = new OkHttpClient();
        String url = getString(R.string.url)+"/back/getstaticinfo";
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        okhttp3.Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Toast toast = Toast.makeText(getApplicationContext(), "获取信息失败", Toast.LENGTH_SHORT);
                toast.show();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 判断是否成功
                final String isSuccess = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (isSuccess.equals("404"))
                            Toast.makeText(BackStatisticalInformation.this, "404", Toast.LENGTH_SHORT).show();
                        else {
                            StaticDataBean data = JsonTransformation.jsonToObject(isSuccess, StaticDataBean.class);
                            Message message = handler.obtainMessage();
                            message.obj = data;
                            handler.sendMessage(message);
                        }
                    }
                });
            }
        });
    }

    public void showMyDialog() {

        final LoadingDialog dialog = new LoadingDialog(this);//=============上下文

        dialog.show();

        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));

        Handler handler = new Handler();

        handler.postDelayed(new Runnable() {

            @Override

            public void run() {

                dialog.dismiss();

            }

        }, 1000);//================动画的时间

    }

    public void back(View view) {
        this.finish();
    }
}
